<template>
  <div class="lb-system-other">
    <top-nav />
    <div class="page-main">
      <el-form
        @submit.native.prevent
        :model="subForm"
        :rules="subFormRules"
        ref="subForm"
        label-width="160px"
      >
        <el-form-item label="订单超时" prop="over_time">
          <el-input v-model.number="subForm.over_time" placeholder="请输入分钟">
            <template slot="append">分钟</template>
          </el-input>
          <lb-tool-tips
            >订单未支付超时时间，超时将自动取消订单，单位：分钟</lb-tool-tips
          >
        </el-form-item>
        <el-form-item label="时间间隔" prop="time_interval">
          <el-input
            v-model.number="subForm.time_interval"
            placeholder="请输入分钟"
          >
            <template slot="append">分钟</template>
          </el-input>
          <lb-tool-tips
            >{{
              $t('action.attendantName')
            }}结束上一单之后，与下一单的时间无间隔导致{{
              $t('action.attendantName')
            }}不能赶到下一个服务点
            <div class="mt-sm">可设置订单间隔，例如设置订单间隔为30分钟</div>
            <div class="mt-sm">
              上一个订单预约时间是14:00-15:00，则下一个用户预约同一个{{
                $t('action.attendantName')
              }}的开始时间为15:30之后
            </div></lb-tool-tips
          >
        </el-form-item>
        <el-form-item label="最长预约" prop="max_day">
          <el-select v-model="subForm.max_day" placeholder="请选择">
            <el-option
              v-for="item in longOptions"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            ></el-option>
          </el-select>
          <lb-tool-tips>客户预约服务选择时间时可选择的时间期限</lb-tool-tips>
        </el-form-item>
        <el-form-item label="时长单位" prop="time_unit">
          <el-select v-model="subForm.time_unit" placeholder="请选择">
            <el-option
              v-for="item in timeOptions"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            ></el-option>
          </el-select>
          <lb-tool-tips>划分工作时间的时间单位</lb-tool-tips>
        </el-form-item>
        <el-form-item label="平台联系电话" prop="mobile">
          <el-input
            v-model="subForm.mobile"
            placeholder="请输入平台联系电话"
          ></el-input>
          <lb-tool-tips
            >用于客户咨询，请填写有效的联系电话，支持400电话
            <div class="mt-sm">400电话格式：400-xxxxxxx</div>
          </lb-tool-tips>
        </el-form-item>
        <el-form-item label="服务开始语音" prop="service_start_recording">
          <div class="flex-warp">
            <div class="lb-file-input flex-between">
              <div :class="[{ 'c-title': subForm.service_start_recording }]">
                {{ subForm.service_start_recording | handleFileName() }}
              </div>
              <div class="flex-center">
                <i
                  @click="toResetFile('service_start_recording')"
                  class="c-warning iconfont icon-guanbi-fill pl-sm pr-sm"
                  v-if="subForm.service_start_recording"
                ></i>
                <lb-cover
                  type="button"
                  fileType="audio"
                  :fileSize="1"
                  @selectedFiles="getFile($event, 'service_start_recording')"
                ></lb-cover>
              </div>
            </div>
            <lb-tool-tips>
              当{{
                $t('action.attendantName')
              }}点击开始服务时，自动播放此音频文件
            </lb-tool-tips>
          </div>
        </el-form-item>
        <el-form-item label="服务结束倒计时语音" prop="countdown_voice">
          <div class="flex-warp">
            <div class="lb-file-input flex-between">
              <div :class="[{ 'c-title': subForm.countdown_voice }]">
                {{ subForm.countdown_voice | handleFileName() }}
              </div>

              <div class="flex-center">
                <i
                  @click="toResetFile('countdown_voice')"
                  class="c-warning iconfont icon-guanbi-fill pl-sm pr-sm"
                  v-if="subForm.countdown_voice"
                ></i>
                <lb-cover
                  type="button"
                  fileType="audio"
                  :fileSize="1"
                  @selectedFiles="getFile($event, 'countdown_voice')"
                ></lb-cover>
              </div>
            </div>
            <lb-tool-tips>
              <div>
                当{{
                  $t('action.attendantName')
                }}点击开始服务，若订单服务总时长大于5分钟，则距离服务结束5分钟时，自动播放此音频文件
              </div>
              <div class="mt-md">
                1）此音频仅在{{
                  $t('action.attendantName')
                }}端的订单列表页（仅在点击【开始服务】且未退出列表页面时有效）、订单详情页播放
              </div>
              <div class="mt-md">
                2）如有多个订单点击开始服务，则按照时间先后依次播报，当第二个订单到达播报时间时，若第一个订单尚未播报完毕则暂停并重新播报
              </div>
            </lb-tool-tips>
          </div>
        </el-form-item>
        <el-form-item label="服务结束语音" prop="service_end_recording">
          <div class="flex-warp">
            <div class="lb-file-input flex-between">
              <div
                class="ellipsis"
                :class="[{ 'c-title': subForm.service_end_recording }]"
              >
                {{ subForm.service_end_recording | handleFileName() }}
              </div>
              <div class="flex-center">
                <i
                  @click="toResetFile('service_end_recording')"
                  class="c-warning iconfont icon-guanbi-fill pl-sm pr-sm"
                  v-if="subForm.service_end_recording"
                ></i>
                <lb-cover
                  type="button"
                  fileType="audio"
                  :fileSize="1"
                  @selectedFiles="getFile($event, 'service_end_recording')"
                ></lb-cover>
              </div>
            </div>
            <lb-tool-tips>
              当{{ $t('action.attendantName') }}服务结束时，自动播放此音频文件
            </lb-tool-tips>
          </div>
        </el-form-item>
        <el-form-item label="客服类型" prop="im_type">
          <el-radio-group v-model="subForm.im_type">
            <el-radio :label="1">平台电话</el-radio>
            <el-radio :label="2" v-if="routesItem.auth.wechat"
              >小程序客服</el-radio
            >
          </el-radio-group>
          <lb-tool-tips
            >勾选平台电话，用户可直接拨打平台的电话号码
            <p class="mt-sm" v-if="routesItem.auth.wechat">
              勾选小程序客服会直接对接小程序客服，在腾讯小程序官方后台添加客服后，可连接对话；仅对小程序端有效
            </p>
          </lb-tool-tips>
        </el-form-item>
        <el-form-item label="匿名评价" prop="anonymous_evaluate">
          <el-radio-group v-model="subForm.anonymous_evaluate">
            <el-radio :label="1">{{ $t('action.ON') }}</el-radio>
            <el-radio :label="0">{{ $t('action.OFF') }}</el-radio>
          </el-radio-group>
          <lb-tool-tips
            >开启之后，手机用户端的评价不显示真实头像和真实昵称
          </lb-tool-tips>
        </el-form-item>
        <el-form-item label="是否派单" prop="order_dispatch">
          <el-radio-group v-model="subForm.order_dispatch">
            <el-radio :label="1">{{ $t('action.ON') }}</el-radio>
            <el-radio :label="0">{{ $t('action.OFF') }}</el-radio>
          </el-radio-group>
          <lb-tool-tips
            >开启派单后，{{
              $t('action.attendantName')
            }}拒单，则不会自动给客户进入退款环节，会进入派单环节，由平台客服人员手动派单给其他人员
          </lb-tool-tips>
        </el-form-item>
        <el-form-item
          :label="'客户联系' + $t('action.attendantName')"
          prop="order_contact_coach"
        >
          <el-radio-group v-model="subForm.order_contact_coach">
            <el-radio :label="1">{{ $t('action.ON') }}</el-radio>
            <el-radio :label="0">{{ $t('action.OFF') }}</el-radio>
          </el-radio-group>
          <lb-tool-tips
            >关闭之后，用户在移动端 - 订单详情里，不可以拨打{{
              $t('action.attendantName')
            }}的联系方式
          </lb-tool-tips>
        </el-form-item>
        <el-form-item
          label="服务过程录音"
          prop="service_recording_show"
          v-if="routesItem.auth.recording"
        >
          <el-radio-group v-model="subForm.service_recording_show">
            <el-radio :label="1">{{ $t('action.ON') }}</el-radio>
            <el-radio :label="0">{{ $t('action.OFF') }}</el-radio>
          </el-radio-group>
          <lb-tool-tips
            >开启后，{{
              $t('action.attendantName')
            }}点击开始服务按钮后，将自动录音，直至服务结束
          </lb-tool-tips>
        </el-form-item>
        <block v-if="routesItem.userInfo.is_admin === 1">
          <el-form-item label="后台登录需短信验证" prop="login_phone_auth">
            <el-radio-group v-model="subForm.login_phone_auth">
              <el-radio :label="1">{{ $t('action.ON') }}</el-radio>
              <el-radio :label="0">{{ $t('action.OFF') }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="平台管理员手机号"
            prop="login_auth_phone"
            v-if="subForm.login_phone_auth === 1"
          >
            <el-input
              v-model="subForm.login_auth_phone"
              placeholder="请输入平台管理员手机号"
            ></el-input>
            <lb-tool-tips
              >当开启后台登录需短信验证时，该手机号用于admin账号登录获取短信验证码
              <div class="mt-sm">请填写有效的联系电话</div></lb-tool-tips
            >
          </el-form-item>
        </block>
        <el-form-item label="强制登录" prop="force_login">
          <el-radio-group v-model="subForm.force_login">
            <el-radio :label="1">{{ $t('action.ON') }}</el-radio>
            <el-radio :label="2">{{ $t('action.OFF') }}</el-radio>
          </el-radio-group>
          <lb-tool-tips
            >当选择开启强制登录时：
            <div class="mt-sm">
              1、若用户未登录，则在{{
                $t('action.attendantName')
              }}列表不能查看图片以及详情信息
            </div>
            <div class="mt-sm">
              2、若用户已登录且在未绑定手机号的情况下，在页面触发绑定手机号弹窗时，该弹窗将没有取消按钮
            </div>
          </lb-tool-tips>
        </el-form-item>
        <el-form-item label="用户实时定位" prop="realtime_location">
          <el-radio-group v-model="subForm.realtime_location">
            <el-radio :label="1">{{ $t('action.ON') }}</el-radio>
            <el-radio :label="0">{{ $t('action.OFF') }}</el-radio>
          </el-radio-group>
          <lb-tool-tips
            >开启实时定位后，手机端首页展示的服务项目根据用户定位来展示该城市的服务项目，如果该城市没有代理商添加服务，默认显示平台添加的服务项目

            <div class="mt-md">
              实时定位需频繁使用腾讯地图的“逆地址解析（位置描述）”功能，个人开发者限制调用量上限（10000次/日），企业开发者限制调用量上限（3,000,000次/日）
            </div>
            <div class="mt-sm">
              请登录腾讯地图开发者平台，确认调用量限制数量，若还未认证企业开发者，建议尽快认证
            </div>
            <div class="mt-lg">
              <a
                class="c-link cursor-pointer"
                href="https://docs.qq.com/doc/DWmRFUFRMRVRxQ0Rj"
                target="_blank"
                >如何查看腾讯地图应用配额？</a
              >
            </div>
            <div class="mt-md c-warning">
              开启实时定位后，在以下情况将自动获取用户当前所在地址：
              <div class="mt-sm">1)、用户首次进入系统</div>
              <div class="mt-sm">
                2)、切换【首页/{{ $t('action.attendantName')
                }}{{ routesItem.auth.map ? '/地图找人' : '' }}】等页面
              </div>
              <div class="mt-sm">
                3)、在【首页/{{ $t('action.attendantName')
                }}{{ routesItem.auth.map ? '/地图找人' : '' }}】页面下拉刷新
              </div>
            </div>
          </lb-tool-tips>
        </el-form-item>
        <el-form-item label="订单通知弹窗提醒" prop="order_tmpl_notice">
          <el-radio-group v-model="subForm.order_tmpl_notice">
            <el-radio :label="1">{{ $t('action.ON') }}</el-radio>
            <el-radio :label="0">{{ $t('action.OFF') }}</el-radio>
          </el-radio-group>
          <lb-tool-tips
            >选择开启，当有来单/退款/拒单/未接单/服务迟到/跳单预警通知时，将在后台任何页面弹出弹窗
            <div class="mt-sm">
              如不选择忽略或是去查看，弹窗将不会关闭。或是可以在通知中心将通知状态处理为已读
            </div>
          </lb-tool-tips>
        </el-form-item>
        <el-form-item label="公众号模板通知" prop="wechat_tmpl">
          <el-radio-group v-model="subForm.wechat_tmpl">
            <el-radio :label="1">{{ $t('action.ON') }}</el-radio>
            <el-radio :label="0">{{ $t('action.OFF') }}</el-radio>
          </el-radio-group>
          <lb-tool-tips
            >选择开启，需要配置订单服务通知模板ID、公众号通知人员，当遇到以下情况，将通知关联人员和订单所属{{
              $t('action.attendantName')
            }}的关联代理商
            <div class="mt-md">1、{{ $t('action.attendantName') }}拒单</div>
            <div class="mt-sm">
              2、{{ $t('action.attendantName') }}长时间不接单
            </div>
            <div class="mt-sm">
              3、{{ $t('action.attendantName') }}迟到预警通知，{{
                $t('action.attendantName')
              }}未按照订单开始时间到达目的地
            </div>
            <div class="mt-sm">
              4、{{ $t('action.attendantName') }}接私单预警，{{
                $t('action.attendantName')
              }}结束订单后，长时间未离开
            </div>
            <div class="mt-md c-warning">
              温馨提示：
              <div class="ml-md mt-sm">
                1)、订单服务通知模板ID在【系统设置 - 公众号通知】中设置
              </div>
              <div class="ml-md mt-sm">
                2)、未接单、服务迟到、跳单预警与【{{
                  $t('action.attendantName')
                }}管理 -
                {{
                  $t('action.attendantName')
                }}设置】中对应内容相关，开启通知请确保已配置
              </div>
            </div>
          </lb-tool-tips>
        </el-form-item>
        <el-form-item
          label="公众号通知人员"
          prop="wechat_tmpl_admin"
          v-if="subForm.wechat_tmpl"
        >
          <el-tag type="danger" class="cursor-pointer" @click="toShowDialog"
            >选择关联用户
          </el-tag>
          <el-table
            :data="subForm.wechat_tmpl_admin"
            :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
            class="mt-lg"
            style="width: 100%"
          >
            <el-table-column prop="id" label="用户ID"></el-table-column>
            <el-table-column prop="avatarUrl" label="头像">
              <template slot-scope="scope">
                <lb-image :src="scope.row.avatarUrl" />
              </template>
            </el-table-column>
            <el-table-column prop="nickName" label="昵称"></el-table-column>
            <el-table-column prop="phone" label="手机号"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <div class="table-operate">
                  <lb-button
                    size="mini"
                    plain
                    type="danger"
                    @click="confirmDel(scope.row.id)"
                    >{{ $t('action.delete') }}</lb-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item>
          <lb-button @click="submitFormInfo" type="primary" v-preventReClick>{{
            $t('action.submit')
          }}</lb-button>
        </el-form-item>
      </el-form>

      <el-dialog
        title="关联用户"
        :visible.sync="showDialog"
        width="800px"
        center
      >
        <el-form
          :inline="true"
          :model="searchForm"
          ref="searchForm"
          label-width="70px"
          class="dialog-form"
        >
          <el-form-item label="输入查询" prop="nickName">
            <el-input
              v-model="searchForm.nickName"
              placeholder="请输入微信昵称/手机号"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <lb-button
              size="medium"
              type="primary"
              icon="el-icon-search"
              style="margin-right: 5px"
              @click="getTableDataList(1)"
              >{{ $t('action.search') }}</lb-button
            >
            <lb-button
              size="medium"
              icon="el-icon-refresh-left"
              style="margin-right: 5px"
              @click="resetForm('searchForm')"
              >{{ $t('action.reset') }}</lb-button
            >
          </el-form-item>
        </el-form>
        <el-table
          :data="tableData"
          ref="multipleTable"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="用户ID"></el-table-column>
          <el-table-column prop="avatarUrl" label="头像">
            <template slot-scope="scope">
              <lb-image :src="scope.row.avatarUrl" />
            </template>
          </el-table-column>
          <el-table-column prop="nickName" label="昵称"></el-table-column>
          <el-table-column prop="phone" label="手机号"></el-table-column>
        </el-table>
        <lb-page
          :batch="false"
          :page="searchForm.page"
          :pageSize="searchForm.limit"
          :total="total"
          @handleSizeChange="handleSizeChange"
          @handleCurrentChange="handleCurrentChange"
        >
        </lb-page>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog = false">取 消</el-button>
          <el-button
            type="primary"
            @click="handleDialogConfirm"
            v-preventReClick
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  data () {
    const checkAdminPhone = (rule, value, callback) => {
      if (this.subForm.login_phone_auth && (!value || !/^1[3-9]\d{9}$/.test(value))) {
        callback(new Error(!value ? '请输入平台管理员手机号' : '请输入有效的平台管理员手机号'))
      } else {
        callback()
      }
    }
    let checkNoticeUser = (rule, value, callback) => {
      if (this.subForm.wechat_tmpl && (!value || value.length === 0)) {
        callback(new Error(`${rule.message}`))
      } else {
        callback()
      }
    }
    return {
      longOptions: [{ id: 3, title: '近3天' }, { id: 5, title: '近5天' }, { id: 7, title: '近7天' }],
      timeOptions: [{ id: 30, title: '半小时' }, { id: 60, title: '一小时' }, { id: 120, title: '两小时' }],
      subForm: {
        over_time: '',
        time_interval: '',
        service_cover_time: '',
        max_day: '',
        time_unit: '',
        mobile: '',
        login_phone_auth: 0,
        login_auth_phone: '',
        service_start_recording: '',
        countdown_voice: '',
        service_end_recording: '',
        im_type: 1,
        anonymous_evaluate: 0,
        order_dispatch: 0,
        order_contact_coach: 0,
        service_recording_show: 0,
        force_login: 0,
        realtime_location: 0,
        order_tmpl_notice: 0,
        wechat_tmpl: 0,
        wechat_tmpl_admin: []
      },
      subFormRules: {
        over_time: { required: true, validator: this.$reg.isNum, reg_type: 2, text: '分钟数', trigger: 'blur' },
        time_interval: { required: true, validator: this.$reg.isNum, reg_type: 2, text: '分钟数', trigger: 'blur' },
        max_day: { required: true, type: 'number', message: '请选择最长预约', trigger: 'blur' },
        time_unit: { required: true, type: 'number', message: '请选择时长单位', trigger: 'blur' },
        mobile: { required: true, validator: this.$reg.isAllPhone, trigger: 'blur' },
        im_type: { required: true, type: 'number', message: '请选择客服类型', trigger: 'blur' },
        anonymous_evaluate: { required: true, type: 'number', message: '请选择匿名评价', trigger: 'blur' },
        order_dispatch: { required: true, type: 'number', message: '请选择是否派单', trigger: 'blur' },
        order_contact_coach: { required: true, type: 'number', message: '请选择客户联系' + this.$t('action.attendantName'), trigger: 'blur' },
        service_recording_show: { required: true, type: 'number', message: '请选择服务过程录音', trigger: 'blur' },
        login_phone_auth: { required: true, type: 'number', message: '请选择', trigger: 'blur' },
        login_auth_phone: { required: true, validator: checkAdminPhone, trigger: 'blur' },
        force_login: { required: true, type: 'number', message: '请选择', trigger: 'blur' },
        realtime_location: { required: true, type: 'number', message: '请选择', trigger: 'blur' },
        order_tmpl_notice: { required: true, type: 'number', message: '请选择', trigger: 'change' },
        wechat_tmpl: { required: true, type: 'number', message: '请选择', trigger: 'change' },
        wechat_tmpl_admin: { required: true, validator: checkNoticeUser, message: '请选择公众号通知人员', trigger: 'blur' }
      },
      searchForm: {
        page: 1,
        limit: 10,
        nickName: ''
      },
      total: 0,
      loading: false,
      tableData: [],
      multipleSelection: [],
      showDialog: false
    }
  },
  created () {
    this.getFormInfo()
  },
  computed: {
    ...mapState({
      routesItem: state => state.routes
    })
  },
  methods: {
    async getFormInfo () {
      let { code, data } = await this.$api.system.configInfo()
      if (code !== 200) return
      data.wechat_tmpl_admin = typeof (data.wechat_tmpl_admin) === 'string' ? [] : data.wechat_tmpl_admin
      for (let i in this.subForm) {
        this.subForm[i] = data[i]
      }
    },
    getFile (file, key) {
      let len = file.length - 1
      this.subForm[key] = file[len].url
    },
    toResetFile (key) {
      this.subForm[key] = ''
    },
    async toShowDialog () {
      this.searchForm.nickName = ''
      await this.getTableDataList()
      this.showDialog = !this.showDialog
    },
    resetForm (form) {
      this.$refs[form].resetFields()
      this.getTableDataList(1)
    },
    handleSizeChange (val) {
      this.searchForm.limit = val
      this.handleCurrentChange(1)
    },
    handleCurrentChange (val) {
      this.searchForm.page = val
      this.getTableDataList()
    },
    async getTableDataList (flag) {
      if (flag) this.searchForm.page = 1
      this.loading = true
      let searchForm = JSON.parse(JSON.stringify(this.searchForm))
      let { code, data } = await this.$api.custom.userList(searchForm)
      this.loading = false
      if (code !== 200) return
      this.tableData = data.data
      this.total = data.total
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    handleDialogConfirm () {
      if (this.multipleSelection.length === 0) {
        this.$message.error(`请选择用户`)
        return
      }
      let user = JSON.parse(JSON.stringify(this.subForm.wechat_tmpl_admin))
      let arr1 = user.length > 0 ? user.map(item => { return item.id }) : []
      this.multipleSelection.map(item => {
        if (arr1.includes(item.id)) return
        user.push(item)
      })
      this.subForm.wechat_tmpl_admin = user
      this.showDialog = false
    },
    confirmDel (id) {
      let index = this.subForm.wechat_tmpl_admin.findIndex(item => {
        return item.id === id
      })
      this.subForm.wechat_tmpl_admin.splice(index, 1)
    },
    submitFormInfo () {
      this.$refs['subForm'].validate(valid => {
        if (valid) {
          let subForm = JSON.parse(JSON.stringify(this.subForm))
          subForm.wechat_tmpl_admin = this.$util.getItems(subForm.wechat_tmpl_admin)
          this.$api.system.configUpdate(subForm).then(res => {
            if (res.code === 200) {
              this.$message.success(this.$t('tips.successSub'))
            }
          })
        }
      })
    }
  },
  filters: {
    handleFileName (url) {
      let text = '请上传文件'
      if (url) {
        text = url.substring(url.lastIndexOf('/') + 1)
      }
      return text
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-system-other {
  width: 100%;

  .el-input,
  .el-select {
    width: 300px;
  }
  .dialog-form {
    .el-input {
      width: 300px;
    }
  }
}
</style>
